{% extends "./base.html" %}

{% load admin_utils %}

{% block main_content %}
<div id="app-memberships-wrapper">
    <bk-dialog header-position="left" v-model="form.visible" theme="primary" width="550" :ok-text="'确定'" :confirm-fn="form.type === 'create'? bulkCreate : singleEdit">
        <div slot="header">$[ form.type === 'create'?'添加':'编辑' ]用户</div>
        <bk-form>
            <bk-form-item label="用户名">
                <bk-input v-if="form.type === 'edit'" style="width: 250px;" v-model="form.usernameList" :readonly="true"></bk-input>
                <user-selector style="width: 250px;" v-model="form.usernameList" v-else-if="form.provider_type === '2' || form.provider_type === '3'"></user-selector>
                <bk-tag-input style="width: 250px;"  v-model="form.usernameList" allow-create v-else></bk-tag-input>
            </bk-form-item>
            <bk-form-item label="用户类型">
                <bk-input v-if="form.type === 'edit'" style="width: 250px;" :value="getTypeName(form.provider_type)" :readonly="true"></bk-input>
                <bk-select v-else v-model="form.provider_type" style="width: 250px;" ext-cls="select-custom" ext-popover-cls="select-popover-custom" searchable>
                    <bk-option v-for="(value, key) in PROVIDER_TYPE"
                        :key="key"
                        :id="key"
                        :name="value">
                    </bk-option>
                </bk-select>
            </bk-form-item>
            <bk-form-item label="角色">
                <bk-select v-model="form.role" style="width: 250px;" ext-cls="select-custom" ext-popover-cls="select-popover-custom" searchable>
                    <bk-option v-for="(value, key) in SITE_ROLE"
                        :key="key"
                        :id="key"
                        :name="value">
                    </bk-option>
                </bk-select>
            </bk-form-item>
        </bk-form>
    </bk-dialog>

    <div class="toolbar">
        <bk-button theme="primary" title="添加用户" icon="plus" class="mr10" @click="showAddDialog">添加用户</bk-button>
        <div class="toolbar">
            <bk-checkbox v-model="displayRegularUsers" @change="refreshPage">显示所有普通用户</bk-checkbox>
            <div class="paas-search">
                <bk-input
                    placeholder="输入用户名，按 Enter 搜索"
                    :clearable="true"
                    :right-icon="'bk-icon icon-search'"
                    v-model="filterKey"
                    @enter="refreshPage">
                </bk-input>
            </div>
        </div>
    </div>
    <bk-table style="margin-top: 15px;" :data="userProfileList">
        <bk-table-column label="用户类型" prop="user.provider_type" width="100">
            <template slot-scope="props">
                <span>$[ getTypeName(props.row.user.provider_type) ]</span>
            </template>
        </bk-table-column>
        <bk-table-column label="用户名" prop="user.username">
            <template slot-scope="props">
                <span>$[ props.row.user.username ]</span>
            </template>
        </bk-table-column>
        <bk-table-column label="角色">
            <template slot-scope="props">
                <span>$[ getRoleName(props.row.role) ]</span>
            </template>
        </bk-table-column>
        <bk-table-column label="操作">
            <template slot-scope="props">
                <button class="btn btn-link" @click="showEditDialog(props.row)">修改</button>
                <button class="btn btn-link" @click="handleSwitcher(props.row)">
                    <span v-if="props.row.role === 5 || props.row.banned">恢复访问</span>
                    <span v-else style="color: red;">禁止访问</span>
                </button>
            </template>
        </bk-table-column>
    </bk-table>
    <pagination
        class="mt15"
        :current.sync="pagination.curPage"
        :limit="pagination.limit"
        :count="pagination.count"
        :align="'right'"
    />
</div>
{% endblock %}

{% block main_script %}
<script type="text/javascript" charset="utf-8">
    var URLRouter = {
        bulk_create: "{% url 'admin.accountmgr.userprofile.api' %}",
        update: "{% url 'admin.accountmgr.userprofile.api' %}",
        destroy: "{% url 'admin.accountmgr.userprofile.api' %}",
    }

    const SITE_ROLE = {{ SITE_ROLE | to_json }}

    const PROVIDER_TYPE = {{ PROVIDER_TYPE | to_json }}

    const ALL_REGIONS = {{ ALL_REGIONS | to_json }}

    const userProfileList = {{ user_profile_list | to_json }}

    const pagination = {{ pagination | to_json }}

    const getRoleName = function (value) {
        for(key of Object.keys(SITE_ROLE)){
            if(key === String(value)){
                return SITE_ROLE[key]
            }
        }
        return undefined
    }

    const getTypeName = function (value) {
        for(key of Object.keys(PROVIDER_TYPE)){
            if(key === String(value)){
                return PROVIDER_TYPE[key]
            }
        }
        return undefined
    }

    document.addEventListener('DOMContentLoaded', () => {
        new Vue({
            el: "#app-memberships-wrapper",
            delimiters: ['$[', ']'],
            data: function () {
                return {
                    loading: false,
                    loaded: false,
                    displayRegularUsers: false,
                    filterKey: '',
                    form: {
                        type: '',
                        usernameList: undefined,
                        role: 2,
                        provider_type: '2',
                        visible: false,
                    },
                    userProfileList: userProfileList,
                    SITE_ROLE,
                    PROVIDER_TYPE,
                    pagination: pagination,
                    allRegionList: ALL_REGIONS,
                }
            },
            created: function () {
                const urlParams = new URLSearchParams(window.location.search)
                if (urlParams.has('display_regular_users')) {
                    this.displayRegularUsers = urlParams.get('display_regular_users') === 'true'
                }
                if (urlParams.has('filter_key')) {
                    this.filterKey = urlParams.get('filter_key')
                }
            },
            methods: {
                refreshPage: function () {
                    const urlParams = new URLSearchParams(window.location.search);
                    urlParams.set('display_regular_users', this.displayRegularUsers);
                    urlParams.set('limit', this.pagination.limit);
                    // 更新页面后回到第一页
                    urlParams.set('offset', '0');
                    urlParams.set('filter_key', this.filterKey);
                    window.location.href = '?' + urlParams.toString();
                },

                showAddDialog: function () {
                    this.form.type = 'create'
                    this.form.visible = true
                    this.form.usernameList = undefined
                    this.form.role = 2
                    this.form.provider_type = '2'
                },

                showEditDialog: function (row) {
                    this.form.type = 'edit'
                    this.form.visible = true
                    this.form.usernameList = row.user.username
                    this.form.role = row.role
                    this.form.provider_type = row.user.provider_type
                },

                handleSwitcher: function (row) {
                    const action = (row.role === 5 || row.banned) ? '恢复访问' : '禁止访问'
                    const confirmAction = () => {
                        if (row.role === 5 || row.banned) {
                            if (row.user.provider_type === 9) {
                                row.role = 50
                            } else {
                                row.role = 2
                            }
                            this.handleChange(row)
                        } else {
                            // 禁止用户访问
                            this.$http.delete(URLRouter.destroy,
                                {
                                    params: {
                                        username: row.user.username,
                                        provider_type: row.user.provider_type,
                                    }
                                }
                            ).then(() => {
                                this.refreshPage()
                            })
                        }
                    }

                    this.$bkInfo({
                        title: `确认要${action}？`,
                        confirmLoading: true,
                        theme: action === '恢复访问' ? 'primary' : 'danger',
                        confirmFn: async () => {
                            try {
                                await confirmAction()
                            } catch (e) {
                                this.$bkMessage({
                                    theme: 'error',
                                    message: e.response.data.detail,
                                })
                            }
                        }
                    })
                },

                bulkCreate: function () {
                    this.$http.post(URLRouter.bulk_create,
                        {
                            username_list: this.form.usernameList,
                            provider_type: this.form.provider_type,
                            role: this.form.role,
                        }
                    ).then(() => {
                        this.refreshPage()
                    })
                    this.form.visible = false
                },
                singleEdit: function () {
                    this.$bkInfo({
                        title: '确定要修改吗？',
                        confirmLoading: true,
                        theme: 'primary',
                        confirmFn: async () => {
                            try {
                                await this.$http.put(URLRouter.update, {
                                    username: this.form.usernameList,
                                    provider_type: this.form.provider_type,
                                    role: this.form.role,
                                })
                                this.refreshPage()
                                this.form.visible = false
                            } catch (e) {
                                this.$bkMessage({
                                    theme: 'error',
                                    message: e.response.data.detail,
                                })
                            }
                        }
                    })
                },
                handleChange: function (row) {
                    if (row.role === "") {
                        row.banned = true
                        return
                    }
                    this.$http.put(URLRouter.update, {
                        username: row.user.username,
                        provider_type: row.user.provider_type,
                        role: row.role,
                    }).then(() => {
                        this.refreshPage()
                    })
                },
                getRoleName,
                getTypeName,
                searchUser: function () {

                }
            }
        })
    })
</script>
<style>
    .toolbar{
        justify-content: space-between;
        display: flex;
        align-items:center;
    }
    .paas-search {
        width: 400px;
        margin-left: 15px;
    }
    .avatar{
        width: 36px;
        height: 36px;
        border: 1px solid #efefef;
    }
</style>
{% endblock %}
